# 中国象棋
import pygame
import sys

# 初始化Pygame
pygame.init()

# 设置窗口大小
screen_width = 800
screen_height = 800
screen = pygame.display.set_mode((screen_width, screen_height))

# 设置标题
pygame.display.set_caption("中国象棋")

# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)

# 棋盘参数
board_width = 9
board_height = 10
cell_size = 80

# 棋子图像加载
chess_images = {
    '红车': pygame.image.load('images/头像.jpg'),
    '红马': pygame.image.load('images/头像.jpg'),
    '红象': pygame.image.load('images/头像.jpg'),
    '红士': pygame.image.load('images/头像.jpg'),
    '红将': pygame.image.load('images/头像.jpg'),
    '红兵': pygame.image.load('images/头像.jpg'),
    '黑车': pygame.image.load('images/头像.jpg'),
    '黑马': pygame.image.load('images/头像.jpg'),
    '黑象': pygame.image.load('images/头像.jpg'),
    '黑士': pygame.image.load('images/头像.jpg'),
    '黑将': pygame.image.load('images/头像.jpg'),
    '黑兵': pygame.image.load('images/头像.jpg')
}

# 初始化棋盘
def init_board():
    board = [[' ' for _ in range(board_width)] for _ in range(board_height)]
    pieces = ['车', '马', '象', '士', '将', '士', '象', '马', '车']
    for i, piece in enumerate(pieces):
        board[0][i] = f'红{piece}'
        board[9][i] = f'黑{piece}'

    for i in range(board_width):
        board[3][i] = '红兵'
        board[6][i] = '黑兵'
    return board

# 绘制棋盘
def draw_board(board):
    for y in range(board_height):
        for x in range(board_width):
            rect = pygame.Rect(x * cell_size, y * cell_size, cell_size, cell_size)
            pygame.draw.rect(screen, black if (x + y) % 2 == 0 else white, rect, 1)
            piece = board[y][x]
            if piece != ' ':
                img = chess_images[piece]
                screen.blit(img, rect)

# 主循环
board = init_board()
selected_piece = None
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            x, y = pygame.mouse.get_pos()
            col = x // cell_size
            row = y // cell_size
            if selected_piece is None:
                piece = board[row][col]
                if piece != ' ':
                    selected_piece = (row, col)
            else:
                if board[selected_piece[0]][selected_piece[1]] != ' ':
                    board[row][col] = board[selected_piece[0]][selected_piece[1]]
                    board[selected_piece[0]][selected_piece[1]] = ' '
                    selected_piece = None

    screen.fill(white)
    draw_board(board)

    pygame.display.flip()

# 清理并退出Pygame
pygame.quit()
sys.exit()